﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Entities;
using Context;
namespace WCF_ListenMusic.Services.Module_Message.User
{
    
    [ServiceBehavior(TransactionAutoCompleteOnSessionClose=true)]
    public class MessageService : IMessageService
    {
        Connect_DBDataContext context = new Connect_DBDataContext();


        #region Add Message
        [OperationBehavior(TransactionAutoComplete=true,TransactionScopeRequired=true)]
        public bool AddMessage(Message message)
        {
            try
            {
                context.Messages.InsertOnSubmit(message);
                context.SubmitChanges();
                return true;
            }
            catch (FaultException ex)
            {
                return false;
                throw new FaultException(ex.Message);
            }
        }

        #endregion

        #region Add Message Recipient

        
        public bool AddMessageRe(MessageRecipient messageRe)
        {
            try
            {
                List<int> q = (from m in context.Messages
                               select m.MessageID).ToList();
                messageRe.MessageID = q.LastOrDefault();
                context.MessageRecipients.InsertOnSubmit(messageRe);
                context.SubmitChanges();
                return true;
            }
            catch (FaultException ex)
            {
                return false;
                throw new FaultException(ex.Message);
            }
        }

        #endregion

        #region Load Message By User


        public List<VW_Message> LoadMessageByUser(string username,string type)
        {
            try
            {
                if (username == null || type == null)
                {
                    throw new FaultException("Username trống hoặc Type trống");
                }
                else
                {
                    var q = from vm in context.VW_Messages
                            where vm.UserReceive.Equals(username) && vm.MessageStyle.Equals(type) && vm._Status.Equals(0)
                            select vm;
                    return q.ToList();
                }
            }
            catch (FaultException ex)
            {
                throw new FaultException(ex.Message);
            }
        }

        #endregion
    }
}
